package org.xxpay.pay.channel.testpay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: 压力测试通道回调
 */
@Service
public class TestpayPayNotifyService extends BasePayNotify {

    private static final MyLog _log = MyLog.getLog(TestpayPayNotifyService.class);
    private static final String logPrefix = "【处理" + TestpayConfig.CHANNEL_NAME + "支付回调】";


    @Override
    public String getChannelName() {
        return TestpayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {
        _log.info("====== 开始处理支付回调通知 ======");
        HttpServletRequest req = (HttpServletRequest) notifyData;
        JSONObject retObj = new JSONObject();

        PayOrder payOrder = verifyParams(req);

        if( payOrder == null ) { //验证参数失败
            retObj.put(PayConstant.RESPONSE_RESULT, TestpayConfig.RETURN_VALUE_FAIL);
            return retObj;
        }

        // 订单已经支付完成
        if(payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS || payOrder.getStatus() == PayConstant.PAY_STATUS_COMPLETE){
            retObj.put(PayConstant.RESPONSE_RESULT, TestpayConfig.RETURN_VALUE_SUCCESS);
            return retObj;
        }

        int updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId());
        if (updatePayOrderRows != 1) {
            _log.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
            retObj.put(PayConstant.RESPONSE_RESULT, "处理订单失败");
            return retObj;
        }
        _log.info("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);

        // 业务系统后端通知
        payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);
        baseNotify4MchPay.doNotify(payOrder, true);

        retObj.put(PayConstant.RESPONSE_RESULT, TestpayConfig.RETURN_VALUE_SUCCESS);
        return  retObj;
    }

    /**
     * 验证通知参数
     * @return
     */
    private PayOrder verifyParams(HttpServletRequest req) {
        //验证必要参数
        String payOrderId = req.getParameter("payOrderId");
        _log.info("{}验证参数payOrderId={}", logPrefix, payOrderId);
        PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId); // 根据myselfOrderId查单
        if(payOrder == null){
            _log.error("{}查单失败payOrderId={}", logPrefix, payOrderId);
            return null;
        }
        return payOrder;
    }
}
